import tkinter as tk
from tkinter import ttk
import json
import pyttsx3
from utils import parse_marked_text
import re
from tkinter import scrolledtext

class ReciteMode:
    def __init__(self, root, essay_data):
        self.root = root
        self.essay_data = essay_data
        self.current_index = 0
        self.show_english = True
        self.show_chinese = True
        self.show_full_text = False  # 添加全文显示模式标志
        self.english_sentences = []
        self.chinese_sentences = []
        self.is_finished = False
        
        # 初始化语音引擎
        self.engine = pyttsx3.init()
        self.engine.setProperty('rate', 150)  # 设置语速
        
        # 配置样式
        self.configure_styles()
        
        # 创建界面
        self.create_widgets()
        
        # 绑定快捷键
        self.bind_shortcuts()
        
        # 初始化显示
        self.initialize_content()
        
    def configure_styles(self):
        """配置ttkbootstrap样式"""
        style = ttk.Style()
        style.configure("TFrame", background="#f0f0f0")
        style.configure("TLabel", background="#f0f0f0", font=('Microsoft YaHei UI', 12))
        style.configure("TButton", font=('Microsoft YaHei UI', 10))
        
        # 配置句子成分的样式
        style.configure("Subject.TLabel", foreground="#2E86C1")
        style.configure("Predicate.TLabel", foreground="#E74C3C")
        style.configure("Object.TLabel", foreground="#27AE60")
        style.configure("Attribute.TLabel", foreground="#8E44AD")
        style.configure("Adverbial.TLabel", foreground="#D35400")
        style.configure("Complement.TLabel", foreground="#16A085")
        
    def create_widgets(self):
        """创建界面组件"""
        # 创建主框架
        self.main_frame = ttk.Frame(self.root, style="TFrame")
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 创建导航按钮框架
        nav_frame = ttk.Frame(self.main_frame)
        nav_frame.pack(fill=tk.X, pady=(0, 20))
        
        # 添加上一句按钮
        self.prev_button = ttk.Button(
            nav_frame,
            text="上一句 (E)",
            command=self.prev_sentence,
            style="TButton"
        )
        self.prev_button.pack(side=tk.LEFT, padx=5)
        
        # 添加下一句按钮
        self.next_button = ttk.Button(
            nav_frame,
            text="下一句 (R)",
            command=self.next_sentence,
            style="TButton"
        )
        self.next_button.pack(side=tk.LEFT, padx=5)
        
        # 添加朗读按钮
        self.speak_button = ttk.Button(
            nav_frame,
            text="朗读 (S)",
            command=self.speak_sentence,
            style="TButton"
        )
        self.speak_button.pack(side=tk.LEFT, padx=5)
        
        # 添加切换英文显示按钮
        self.toggle_english_button = ttk.Button(
            nav_frame,
            text="切换英文 (D)",
            command=self.toggle_english,
            style="TButton"
        )
        self.toggle_english_button.pack(side=tk.LEFT, padx=5)
        
        # 添加切换中文显示按钮
        self.toggle_chinese_button = ttk.Button(
            nav_frame,
            text="切换中文 (F)",
            command=self.toggle_chinese,
            style="TButton"
        )
        self.toggle_chinese_button.pack(side=tk.LEFT, padx=5)
        
        # 添加切换全文显示按钮
        self.toggle_full_text_button = ttk.Button(
            nav_frame,
            text="切换全文 (A)",
            command=self.toggle_full_text,
            style="TButton"
        )
        self.toggle_full_text_button.pack(side=tk.LEFT, padx=5)
        
        # 添加帮助按钮
        self.help_button = ttk.Button(
            nav_frame,
            text="帮助 (H)",
            command=self.show_help,
            style="TButton"
        )
        self.help_button.pack(side=tk.LEFT, padx=5)
        
        # 创建句子显示区域
        self.sentence_frame = ttk.Frame(self.main_frame)
        self.sentence_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建英文句子显示区域
        self.english_frame = ttk.Frame(self.sentence_frame)
        self.english_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
        
        # 创建中文句子显示区域
        self.chinese_frame = ttk.Frame(self.sentence_frame)
        self.chinese_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建全文显示区域
        self.full_text_frame = ttk.Frame(self.sentence_frame)
        self.full_text_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建进度显示
        self.progress_label = ttk.Label(
            self.main_frame,
            text="",
            style="TLabel"
        )
        self.progress_label.pack(pady=(10, 0))
        
    def bind_shortcuts(self):
        """绑定快捷键"""
        self.root.bind("e", lambda e: self.prev_sentence())
        self.root.bind("r", lambda e: self.next_sentence())
        self.root.bind("s", lambda e: self.speak_sentence())
        self.root.bind("d", lambda e: self.toggle_english())
        self.root.bind("f", lambda e: self.toggle_chinese())
        self.root.bind("h", lambda e: self.show_help())
        self.root.bind("a", lambda e: self.toggle_full_text())  # 修改为调用toggle_full_text方法
        
    def initialize_content(self):
        """初始化内容显示"""
        # 解析英文句子
        english_text = self.essay_data.get("english", "")
        self.english_sentences = [s.strip() for s in english_text.split(".") if s.strip()]
        
        # 解析中文句子
        chinese_text = self.essay_data.get("chinese", "")
        self.chinese_sentences = [s.strip() for s in chinese_text.split("。") if s.strip()]
        
        # 确保中英文句子数量一致
        min_sentences = min(len(self.english_sentences), len(self.chinese_sentences))
        self.english_sentences = self.english_sentences[:min_sentences]
        self.chinese_sentences = self.chinese_sentences[:min_sentences]
        
        # 更新显示
        self.update_display()
        
    def update_display(self):
        """更新显示内容"""
        # 清空现有显示
        for widget in self.english_frame.winfo_children():
            widget.destroy()
        for widget in self.chinese_frame.winfo_children():
            widget.destroy()
        for widget in self.full_text_frame.winfo_children():
            widget.destroy()
            
        if self.show_full_text:
            # 显示全文
            self.show_full_text_content()
        else:
            # 显示单句
            if 0 <= self.current_index < len(self.english_sentences):
                # 更新英文句子显示
                if self.show_english:
                    self.update_english_sentence(self.english_sentences[self.current_index])
                
                # 更新中文句子显示
                if self.show_chinese:
                    self.update_chinese_sentence(self.chinese_sentences[self.current_index])
                
                # 更新进度显示
                self.progress_label.configure(
                    text=f"进度：{self.current_index + 1}/{len(self.english_sentences)}"
                )
                
                # 标记为已完成
                if self.current_index == len(self.english_sentences) - 1 and not self.is_finished:
                    self.is_finished = True
            
    def update_english_sentence(self, sentence):
        """更新英文句子显示"""
        # 解析句子成分
        components = parse_marked_text(sentence)
        
        # 创建标签显示各个成分
        for component in components:
            text = component["text"].strip()
            if text:
                style = f"{component['type'].capitalize()}.TLabel" if component['type'] != 'normal' else "TLabel"
                label = ttk.Label(
                    self.english_frame,
                    text=text,
                    style=style,
                    wraplength=700  # 设置自动换行宽度
                )
                label.pack(side=tk.LEFT, padx=2)
            
    def update_chinese_sentence(self, sentence):
        """更新中文句子显示"""
        # 解析句子成分
        components = parse_marked_text(sentence)
        
        # 创建标签显示各个成分
        for component in components:
            text = component["text"].strip()
            if text:
                style = f"{component['type'].capitalize()}.TLabel" if component['type'] != 'normal' else "TLabel"
                label = ttk.Label(
                    self.chinese_frame,
                    text=text,
                    style=style,
                    wraplength=700  # 设置自动换行宽度
                )
                label.pack(side=tk.LEFT, padx=2)
            
    def prev_sentence(self):
        """显示上一句"""
        if self.current_index > 0:
            self.current_index -= 1
            self.update_display()
            
    def next_sentence(self):
        """显示下一句"""
        if self.current_index < len(self.english_sentences) - 1:
            self.current_index += 1
            self.update_display()
            
    def speak_sentence(self):
        """朗读当前句子"""
        if 0 <= self.current_index < len(self.english_sentences):
            sentence = self.english_sentences[self.current_index]
            # 移除标记
            clean_sentence = re.sub(r'[&*#()\[\]$]', '', sentence)
            self.engine.say(clean_sentence)
            self.engine.runAndWait()
            
    def toggle_english(self):
        """切换英文显示"""
        self.show_english = not self.show_english
        self.update_display()
        
    def toggle_chinese(self):
        """切换中文显示"""
        self.show_chinese = not self.show_chinese
        self.update_display()
        
    def toggle_full_text(self):
        """切换全文显示模式"""
        self.show_full_text = not self.show_full_text
        self.update_display()
        
    def show_help(self):
        """显示帮助信息"""
        help_text = """
快捷键说明：
- E：上一句
- R：下一句
- S：朗读当前句子
- D：切换英文显示/隐藏
- F：切换中文显示/隐藏
- H：显示/隐藏帮助信息
"""
        # 创建帮助窗口
        help_window = tk.Toplevel(self.root)
        help_window.title("帮助")
        help_window.geometry("400x300")
        
        # 创建文本框
        text_widget = tk.Text(help_window, wrap=tk.WORD, font=('Microsoft YaHei UI', 12))
        text_widget.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 插入帮助文本
        text_widget.insert(tk.END, help_text)
        text_widget.config(state=tk.DISABLED)  # 设置为只读
        
        # 添加关闭按钮
        close_button = ttk.Button(help_window, text="关闭", command=help_window.destroy)
        close_button.pack(pady=10)
        
    def show_full_text_content(self):
        """显示全文内容"""
        # 创建文本区域
        text_area = scrolledtext.ScrolledText(self.full_text_frame, wrap=tk.WORD, font=('Microsoft YaHei UI', 12))
        text_area.pack(expand=True, fill='both', padx=10, pady=10)
        
        # 配置标签样式
        text_area.tag_configure("title", font=('Microsoft YaHei UI', 12, 'bold'))
        text_area.tag_configure("current", background="#FFE4B5")  # 高亮当前句子
        text_area.tag_configure("Subject", foreground="#2E86C1")
        text_area.tag_configure("Predicate", foreground="#E74C3C")
        text_area.tag_configure("Object", foreground="#27AE60")
        text_area.tag_configure("Attribute", foreground="#8E44AD")
        text_area.tag_configure("Adverbial", foreground="#D35400")
        text_area.tag_configure("Complement", foreground="#16A085")
        
        # 插入英文内容
        if self.show_english:
            text_area.insert(tk.END, "英文原文：\n\n", "title")
            for i, sentence in enumerate(self.english_sentences):
                # 解析句子成分
                components = parse_marked_text(sentence)
                # 如果是当前句子，添加高亮标签
                if i == self.current_index:
                    text_area.insert(tk.END, sentence + "\n\n", "current")
                else:
                    # 为每个成分添加颜色
                    for component in components:
                        text = component["text"].strip()
                        if text:
                            tag = component['type'].capitalize() if component['type'] != 'normal' else ""
                            text_area.insert(tk.END, text, tag)
                    text_area.insert(tk.END, "\n\n")
            
        # 插入中文内容
        if self.show_chinese:
            text_area.insert(tk.END, "\n中文翻译：\n\n", "title")
            for i, sentence in enumerate(self.chinese_sentences):
                # 如果是当前句子，添加高亮标签
                if i == self.current_index:
                    text_area.insert(tk.END, sentence + "\n\n", "current")
                else:
                    text_area.insert(tk.END, sentence + "\n\n")
            
        # 设置只读
        text_area.configure(state='disabled')
        
        # 更新进度显示
        self.progress_label.configure(
            text=f"全文模式 - 当前句子：{self.current_index + 1}/{len(self.english_sentences)}"
        )